package com.lgw.coupon.service.impl;

import com.lgw.commons.constant.RedisKeyConstant;
import com.lgw.commons.model.pojo.VoucherOrders;
import com.lgw.coupon.mapper.VoucherOrdersMapper;
import com.lgw.coupon.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private VoucherOrdersMapper voucherOrdersMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //生成订单，使用事务保证原子性，如果失败需要恢复信号量
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean generateOrder(VoucherOrders voucherOrders) {
        try {
            voucherOrdersMapper.save(voucherOrders);
        } catch (Exception e) {
            // 手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            String redisKey = RedisKeyConstant.seckill_vouchers.getKey()+voucherOrders.getVoucherId();
            log.info("保存订单失败");
            //恢复库存
            redisTemplate.opsForHash().increment(redisKey,"amount",1);
            //释放占位符
            String lockName = RedisKeyConstant.lock_key.getKey() + voucherOrders.getCustomerId() +
                    voucherOrders.getVoucherId();
            redisTemplate.delete(lockName);
            e.printStackTrace();
        }
        return false;
    }
}
